package com.atguigu.tingshu.account.api;

import com.atguigu.tingshu.account.service.UserAccountDetailService;
import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.login.GuiguLogin;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.account.UserAccount;
import com.atguigu.tingshu.vo.payment.PayVo;
import com.atguigu.tingshu.vo.payment.PaymentVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Tag(name = "用户账户管理")
@RestController
@RequestMapping("/api/account/userAccount")
@SuppressWarnings({"unchecked", "rawtypes"})
public class UserAccountApiController {

	@Autowired
	private UserAccountService userAccountService;
	@Autowired
	private UserAccountDetailService userAccountDetailService;

	/**
	 * 查询用户当前可用余额
	 * @return
	 */
	@GuiguLogin
	@GetMapping("/getAvailableAmount")
	public Result getAvailableAmount(){
		UserAccount userAccount = userAccountService.getOne(
				new LambdaQueryWrapper<UserAccount>()
						.eq(UserAccount::getUserId, AuthContextHolder.getUserId()));
		return Result.ok(userAccount.getAvailableAmount());
	}


	/**
	 * 分页查询用户消费记录
	 * @return
	 */
	@GuiguLogin
	@GetMapping("/findUserConsumePage/{page}/{size}")
	public Result findUserConsumePage(@PathVariable(value = "page") Integer page,
									  @PathVariable(value = "size") Integer size){
		return Result.ok(userAccountService.findUserConsumePage(page,size));
	}

	/**
	 * 分页查询用户充值记录
	 * @return
	 */
	@GuiguLogin
	@GetMapping("/findUserRechargePage/{page}/{size}")
	public Result findUserRechargePage(@PathVariable(value = "page") Integer page,
									  @PathVariable(value = "size") Integer size){
		return Result.ok(userAccountService.findUserRechargePage(page,size));
	}

	/**
	 * 方便测试 实际由付款调用
	 * 账户余额支付 -- 校验即将校验订单是否存在
	 * 从redis中存储的预交易流水中获取:
	 * redis.key = "PrepayId_" + prepayId
	 * redis.value = userAccountDetail
	 * @param key
	 * @return
	 */
	@GetMapping("/accountPay")
	public Result accountPay(@RequestParam String key){
		return Result.ok(userAccountService.accountPay(key));
	}

	/**
	 * 方便测试 实际由付款调用
	 * 提交支付，付款前需校验 -- 一笔流水只能被支付一次
	 * 1. 单笔流水被多人单次付款
	 * 2. 单笔流水被单人多次付款
	 * AfterPaid：
	 * 同步告知用户支付信息
	 * 异步feign调用相关微服务修改相应数据
	 * @param payVo
	 * @return
	 */
	@PostMapping("/pay")
	public Result pay(@RequestBody PayVo payVo){
		userAccountService.pay(payVo);
		return Result.ok();
	}



}

